<!-- 正文开始 -->
<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-card-body">
            <!-- 头部操作栏 -->
            <div class="layui-form lay-header">
                <div class="toolbar">
                    <div class="layui-form-item lay-query-content">
                        <div class="lay-query-box">
                            <div class="query-lt">
                                <div class="layui-inline">
                                    <label class="layui-form-label w-auto">申请单编号：</label>
                                    <div class="layui-input-inline">
                                        <input name="code" class="layui-input" type="text" placeholder="申请单编号"/>
                                    </div>
                                </div>
                                <!-- <div class="layui-inline">
                                     <label class="layui-form-label w-auto">领新记录编号：</label>
                                     <div class="layui-input-inline">
                                         <input name="inventoryOutCode" class="layui-input" type="text"
                                                placeholder="领新记录编号"/>
                                     </div>
                                 </div>-->
                                <div class="layui-inline">
                                    <label class="layui-form-label w-auto">申请人：</label>
                                    <div class="layui-input-inline">
                                        <input name="creatorName" class="layui-input" type="text" placeholder="申请人"/>
                                    </div>
                                </div>
                                <!--<div class="layui-inline">
                                    <label class="layui-form-label w-auto">物料编号：</label>
                                    <div class="layui-input-inline">
                                        <input name="cabinetCode" class="layui-input" type="text" placeholder="物料编号"/>
                                    </div>
                                </div>-->
                                <div class="layui-inline">
                                    <label class="layui-form-label w-auto">所属权限组：</label>
                                    <div class="layui-input-inline">
                                        <input name="authorityManageName" class="layui-input" type="text"
                                               placeholder="所属权限组"/>
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <label class="layui-form-label w-auto">选择刀具柜：</label>
                                    <div class="layui-input-inline">
                                        <select name="mainCabCode">
                                            <option value="">选择刀具柜</option>
                                        </select>
                                        <!--<input name="mainCabCode" class="layui-input" type="text" placeholder="选择刀具柜"/>-->
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <label class="layui-form-label w-auto">申请订单状态：</label>
                                    <div class="layui-input-inline">
                                        <select name="checkStatus">
                                            <option value="">审核状态</option>
                                            <option value="0">待初审</option>
                                            <option value="1">初审驳回</option>
                                            <option value="2">初审通过</option>
                                            <option value="3">待复审</option>
                                            <option value="4">复审驳回</option>
                                            <option value="5">复审通过</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <label class="layui-form-label w-auto">起止时间：</label>
                                    <div class="layui-input-inline">
                                        <input id="pTime" class="layui-input" type="text" placeholder="选择创建时间"
                                               autocomplete="off" readonly/>
                                        <input name="startCreateTime" id="sTime" style="display: none"/>
                                        <input name="endCreateTime" id="eTime" style="display: none"/>
                                    </div>
                                </div>
                            </div>
                            <div class="query-rt">
                                <div class="layui-inline">
                                    <button class="layui-btn icon-btn color-green" lay-filter="formSubSearchLog"
                                            lay-submit layui-form-keyDownSearch="true">查询
                                    </button>
                                    <button class="layui-btn icon-btn color-white" lay-filter="resets" lay-submit>重置
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="lay-btn-rows">
                    <div class="lay-btn-box">
                        <div class="lay-btn-lt" style="min-height: 30px">
                            <!-- <button type="button" id="storesRequisitionBtnAdd" class="layui-btn icon-btn color-reseda">
                                 添加超额申请申请
                             </button>-->
                        </div>
                        <div class="lay-btn-rt">
                        </div>
                    </div>
                </div>
            </div>
            <!-- 表格 -->
            <table class="layui-table" id="storesRequisitionTable" lay-filter="storesRequisitionTable"></table>
        </div>
    </div>
</div>
<style>
    div[lay-id="productDetailTable"] .layui-table-cell {
        padding: 0 5px;
    }
</style>

<!-- 表格操作列 -->
<script type="text/html" id="storesRequisitionTableBar">

    {{# let userData = layui.config.getUser().id }}

    <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="detail">详情</a>

    {{# if(d.checkStatus == "approve" && userData == d.auditPersonId){  }}
    <a class="layui-btn layui-btn-warm layui-btn-xs" lay-event="audit">审核</a>
    {{# }else if(d.checkStatus == "appRCheck" && userData == d.twoAuditPersonId){ }}
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="review">复审</a>
    {{# } }}
</script>


<!--详情弹窗-->
<script type="text/html" id="storesRequisitionDetailTemplate">
    <form lay-filter="storesRequisitionDetailTemplate" class="layui-form model-form form-scroll">
        <div class="open-details-box pd-20 table-bor">
            <div class="layui-form-item" style="margin: 20px 0 10px;">
                <div class="open-details-title">订单信息：</div>
            </div>
            <table class="layui-table" id="storesRequisitionTopTable"
                   lay-filter="storesRequisitionTopTable"></table>

            <div class="layui-form-item" style="margin: 20px 0 10px;">
                <div class="open-details-title">审核信息：</div>
            </div>
            <table class="layui-table" id="auditTable"
                   lay-filter="auditTable"></table>

            <div class="layui-form-item" style="margin: 20px 0 10px;">
                <div class="open-details-title">物料详情：</div>
            </div>
            <table class="layui-table" id="productDetailTable"
                   lay-filter="productDetailTable"></table>


            <div class="layui-form-item" style="margin-top: 20px;" id="isCheckStatus">
                <label class="layui-form-label w-auto">审核状态：</label>
                <div class="layui-input-inline">
                    <select name="checkStatus" id="checkStatus" lay-filter="checkStatus"
                            lay-verify="required">
                        <option value="">请选择</option>
                        <option value="2">审核通过</option>
                        <option value="1">审核驳回</option>
                    </select>
                </div>
                <div class="layui-input-inline" style="width: 300px">
                    <input class="layui-input" type="text" placeholder="审核备注" id="remark"/>
                </div>
            </div>
        </div>
        <div class="layui-form-item text-right pd-20">
            <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">取消</button>
            <button class="layui-btn isCheckStatus" lay-filter="storesRequisitionDetailFormSubmit" lay-submit>提交
            </button>
        </div>
    </form>
</script>

<!-- js部分 -->
<script>
    layui.use(['layer', 'form', 'table', 'admin', 'laydate'], function () {
        const $ = layui.jquery, {layer, form, table, config, admin, laydate} = layui;

        form.render('select');
        admin.req('enterprisecab/cabinet/admin/cabinet/list', {cabinetNature: 'main', cabinetType: 'spring'}, res => {
            if (res.code === 200) {
                loadSelectHtml(res.data, '请选择刀具柜', '.query-lt', 'mainCabCode', 4);
            } else {
                loadSelectHtml([], '请选择刀具柜', '.query-lt', 'mainCabCode', 4);
            }
        }, 'get');

        //时间范围
        laydate.render({
            elem: '#pTime',
            type: 'date',
            range: true,
            done: function (value, date, endDate) {
                if (value) {
                    let dateValue = value.split(" - ");
                    $("input[name='startCreateTime']").val(dateValue[0] + " 00:00:00");
                    $("input[name='endCreateTime']").val(dateValue[1] + " 23:59:59");
                } else {
                    $("input[name='startCreateTime']").val("");
                    $("input[name='endCreateTime']").val("");
                }
                setTimeout(function () {
                    $('[lay-filter="formSubSearchLog"]').click()
                }, 300);
            }
        });

        // 渲染表格
        let insTb = table.render({
            elem: '#storesRequisitionTable',
            url: config.base + 'enterprisecab/cabinet/admin/aboveTheQuotaApply/list',
            toolbar: true,
            defaultToolbar: ["filter"],
            page: true,
            cellMinWidth: 100,
            cols: [[
                {field: 'code', title: '申请单编号'}
                , {field: 'mainCabCode', title: '所属刀柜'}
                , {field: 'quantity', title: '申请数量'}
                , {field: 'totalPrice', title: '申请总金额'}
                , {field: 'authorityManageName', title: '所属权限组'}
                , {
                    field: 'lineOfCredit', title: '授信标准', width: 150, templet: d => {
                        let html = '';
                        if (d.creditType == 'money') {
                            html = '标准额度:' + d.creditAmount + '<br /> 复审额度:' + d.recheckAmount;
                        } else {
                            html = '标准额度:' + d.creditQuantity + '<br /> 复审额度:' + d.recheckAmount;
                        }
                        return html
                    }
                }
                , {
                    field: 'practicalLineOfCredit',
                    title: '当前额度',
                    templet: d => d.creditType == 'money' ? d.practicalLineOfCredit : d.practicalCreditQuantity,
                }
                , {field: 'creatorName', title: '申请人'}
                , {field: 'createTime', title: '申请时间'}
                , {field: 'checkStatusDesc', title: '订单状态'}
                , {field: 'auditPerson', title: '初审人'}
                , {field: 'auditTime', title: '初时间'}
                , {toolbar: '#storesRequisitionTableBar', title: '操作', width: 150}
            ]],
        });

        // 工具条点击事件
        table.on('tool(storesRequisitionTable)', function (obj) {
            let data = obj.data;
            if (obj.event === 'detail') { // 详情
                storesRequisitionDetailModel(data, 'detail');
            } else if (obj.event === 'audit') { // 审核
                storesRequisitionDetailModel(data, 'audit');
            } else if (obj.event === 'review') {
                storesRequisitionDetailModel(data, 'review');
            }
        });

        //监听排序
        table.on('sort(storesRequisitionTable)', function (obj) {
            table.reload('storesRequisitionTable', {
                initSort: obj
                , where: {
                    sort: obj.field
                    , order: obj.type
                }
            });
        });

        // 搜索
        form.on('submit(formSubSearchLog)', function (data) {
            insTb.reload({where: data.field, page: {curr: 1}}, 'data');
        });

        form.on('submit(resets)', function (data) {
            $(".lay-header").find('select').val("");
            $(".lay-header").find('input').val("");
            let field = data.field;
            for (let key in field) {
                field[key] = ''
            }
            insTb.reload({where: field, page: {curr: 1}}, 'data');
        });


        // 显示详情弹窗
        function storesRequisitionDetailModel(data, type) {
            admin.open({
                type: 1,
                area: ['80%', '800px'],
                offset: '65px',
                title: type === 'review' ? '复审超额领新' : (type === 'audit' ? '审核超额领新' : '超额领新详情'),
                content: $('#storesRequisitionDetailTemplate').html(),
                success: function () {

                    // 渲染表格
                    let storesRequisitionTopTable = table.render({
                        elem: '#storesRequisitionTopTable',
                        data: [data],
                        cellMinWidth: 100,
                        cols: [[
                            {field: 'id', title: '超额申请ID'}
                            , {field: 'mainCabCode', title: '所属刀柜'}
                            , {field: 'quantity', title: '产品数量'}
                            , {field: 'totalPrice', title: '货值'}
                            , {field: 'authorityManageName', title: '所属权限组'}
                            , {field: 'creatorName', title: '申请人'}
                            , {field: 'createTime', title: '申请提交时间'}
                            , {field: 'checkStatusDesc', title: '订单状态'}
                        ]],
                    });

                    let productDetailTBData = [];
                    admin.reqSync('enterprisecab/cabinet/admin/aboveTheQuotaApplyProduct/list', {
                        aboveTheQuotaApplyId: data.id,
                        limit: 9999
                    }, res => {
                        if (res.code === 200) {
                            productDetailTBData = res.data;
                        }
                    });

                    let productDetailTB = table.render({
                        elem: '#productDetailTable',
                        // url: config.base + 'enterprisecab/cabinet/admin/aboveTheQuotaApplyProduct/list',
                        // where: {aboveTheQuotaApplyId: data.id, limit: 9999},
                        data: productDetailTBData,
                        cellMinWidth: 80,
                        cols: [[
                            {field: 'skuCode', title: '物料料号'}
                            , {field: 'skuName', title: '物料名称'}
                            , {field: 'productCode', title: '规格系列编号', width: 100}
                            , {field: 'specCode', title: '规格码'}
                            , {field: 'productTypeName', title: '所属类型'}
                            , {field: 'packName', title: '包装方式'}
                            , {field: 'price', title: '单价'}
                            , {field: 'quantity', title: '基础数量'}
                            , {field: 'packUnitName', title: '包装单位'}
                            , {field: 'totalPrice', title: '小计金额'}
                            , {field: 'quantityPack', title: '包装数量'}
                            , {field: 'creditTypeDesc', title: '授信类型', templet: d => data.creditTypeDesc}
                            , {
                                field: 'acturlQuantity', title: '实际申请数量', width: 110, templet: d => {
                                    if (type === 'detail') { //详情
                                        return d.acturlQuantity ? d.acturlQuantity : ''
                                    } else if (type === 'audit') { // 初审审核
                                        return '<input class="layui-input" value="' + d.quantity + '" required  lay-verify="number" name="acturlQuantity"/>'
                                    } else if (type === 'review') { // 复审审核
                                        return '<input class="layui-input" value="' + d.acturlQuantity + '" required  lay-verify="number" name="acturlQuantity"/>'
                                    } else {
                                        return ''
                                    }
                                }
                            }
                            , {
                                field: 'acturlTotalPrice', title: '实际申请金额', width: 110, templet: d => {
                                    if (type === 'detail') { //详情
                                        return d.acturlTotalPrice ? d.acturlTotalPrice : ''
                                    } else if (type === 'audit') { // 初审审核
                                        return '<input class="layui-input" value="' + d.totalPrice + '" required  lay-verify="number" name="acturlTotalPrice"/>'
                                    } else if (type === 'review') { // 复审审核
                                        return '<input class="layui-input" value="' + d.acturlTotalPrice + '" required  lay-verify="number" name="acturlTotalPrice"/>'
                                    } else {
                                        return ''
                                    }
                                }
                            }
                            , {
                                field: 'amount',
                                title: '标准授信额',
                                templet: d => data.creditType == 'money' ? d.amount : d.number
                            }
                            , {
                                field: 'realAmount',
                                title: '实际授信额',
                                templet: d => data.creditType == 'money' ? d.realAmount : d.realNumber
                            }
                        ]],
                    });

                    $("body").delegate("[lay-id='productDetailTable'] input[name='acturlQuantity']", "change", function () {
                        if (productDetailTBData[$(this).parents('tr').index()]) {
                            productDetailTBData[$(this).parents('tr').index()].acturlQuantity = $(this).val().trim();
                        }
                    });

                    $("body").delegate("[lay-id='productDetailTable'] input[name='acturlTotalPrice']", "change", function () {
                        if (productDetailTBData[$(this).parents('tr').index()]) {
                            productDetailTBData[$(this).parents('tr').index()].acturlTotalPrice = $(this).val().trim();
                        }
                    });

                    let auditTB = table.render({
                        elem: '#auditTable',
                        data: [data],
                        cellMinWidth: 100,
                        cols: [[
                            {field: 'creditWayDesc', title: '授信方式'}
                            , {
                                field: 'lineOfCredit', title: '授信标准', width: 180, templet: d => {
                                    let html = '';
                                    if (d.creditType == 'money') {
                                        html = '标准额度：' + d.creditAmount + '<br /> 复审额度：' + d.recheckAmount;
                                    } else {
                                        html = '标准额度：' + d.creditQuantity + '<br /> 复审额度：' + d.recheckAmount;
                                    }
                                    return html
                                }
                            }
                            , {
                                field: 'practicalLineOfCredit',
                                title: '当前额度',
                                templet: d => d.creditType == 'money' ? d.practicalLineOfCredit : d.practicalCreditQuantity
                            }
                            , {field: 'totalPrice', title: '本次申请额度'}
                            , {
                                field: 'practicalLineOfCredit', title: '审后额度', templet: d => {
                                    let limit = d.creditType == 'money' ? d.practicalLineOfCredit : d.practicalCreditQuantity;
                                    return (parseFloat(limit) + parseFloat(d.totalPrice)).toFixed(2)
                                }
                            }
                            , {
                                field: 'lineOfCredit', title: '超标准额度', templet: d => {
                                    let limit = d.creditType == 'money' ? d.practicalLineOfCredit : d.practicalCreditQuantity,
                                        standard = d.creditType == 'money' ? d.creditAmount : d.creditQuantity;

                                    return (parseFloat(limit) + parseFloat(d.totalPrice) - parseFloat(standard)).toFixed(2)
                                }
                            }
                            , {
                                field: 'auditPerson', title: '初审信息', templet: d => {
                                    let html = d.auditPerson + '<br /> 时间：' + d.auditTime;
                                    return html
                                }
                            }
                            , {field: 'auditRemark', title: '初审备注'}
                            , {field: 'recheckAmount', title: '超复审额度'}
                            // , {field: 'isDeleted', title: '是否需要复审', templet: d => d.isDeleted ? '是' : '否'}
                            , {
                                field: 'twoAuditPerson', title: '复审信息', templet: d => {
                                    let html = d.twoAuditPerson + '<br /> 时间：' + d.twoAuditTime;
                                    return html
                                }
                            }
                            , {field: 'rcheckAuditRemark', title: '复审备注'}
                        ]],
                    });

                    let selectData1 = [{name: '初审通过', value: 'toaudit'}, {name: '初审驳回', value: 'reject'}],
                        selectData2 = [{name: '复审通过', value: 'rCheckAudit'}, {name: '复审驳回', value: 'rCheckReject'}];

                    if (type === 'detail') {
                        $('#isCheckStatus').hide();
                        $('button[lay-filter="storesRequisitionDetailFormSubmit"]').hide();
                    } else {
                        $('#isCheckStatus').show();
                        $('button[lay-filter="storesRequisitionDetailFormSubmit"]').show();
                        if (type === 'audit') {
                            loadSelectHtml(selectData1, '请选择初审', 'form[lay-filter="storesRequisitionDetailTemplate"]', 'checkStatus', 3);
                            $('#remark').attr('name', 'auditRemark');
                        } else {
                            loadSelectHtml(selectData2, '请选择复审', 'form[lay-filter="storesRequisitionDetailTemplate"]', 'checkStatus', 3);
                            $('#remark').attr('name', 'rcheckAuditRemark');
                        }
                    }

                    form.render('select');

                    // 提交审核
                    form.on('submit(storesRequisitionDetailFormSubmit)', function (d) {
                        let obj = {
                            remark: d.field.remark,
                            checkStatus: d.field.checkStatus,
                            id: data.id,
                            items: JSON.stringify(productDetailTBData)
                        };
                        layer.load(2);
                        admin.req(type == 'review' ? 'enterprisecab/cabinet/admin/aboveTheQuotaApply/againCheck' : 'enterprisecab/cabinet/admin/aboveTheQuotaApply/firstCheck', obj, function (res) {
                            layer.closeAll('loading');
                            if (res.code == 200) {
                                layer.msg(res.msg, {icon: 1});
                                table.reload('storesRequisitionTable');
                                layer.closeAll();
                            } else {
                                layer.msg(res.msg, {icon: 2});
                            }
                        }, 'get');
                        return false;
                    });
                }
            })
        }

        // option渲染
        function loadSelectHtml(data, tips, parent, htmltarget, type) {
            let html = ' <option value>' + tips + '</option>';
            if (!data || data == null) {
                return;
            }
            for (let i = 0; i < data.length; i++) {
                if (type === 1) {
                    html += `<option value='${data[i].id}'>${data[i].cabCode}</option>`;
                } else if (type === 2) {
                    html += `<option value='${data[i].id}'>${data[i].nickname}</option>`;
                } else if (type === 3) {
                    html += `<option value='${data[i].value}'>${data[i].name}</option>`;
                } else if (type === 4) {
                    html += `<option value='${data[i].cabCode}'>${data[i].cabCode}</option>`;
                }
            }

            $(parent + " select[name='" + htmltarget + "']").html(html);
            form.render('select');
        }

    });
</script>